package com.lsfb.signln.Index;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.View;

import com.gyf.barlibrary.ImmersionBar;
import com.lsfb.signln.Leave.LeaveFragment;
import com.lsfb.signln.Location.LocationFragment;
import com.lsfb.signln.Location.SignIn.SignInFileEvent;
import com.lsfb.signln.Login.Face.FirstFaceActivity;
import com.lsfb.signln.Login.LoginActivity;
import com.lsfb.signln.My.MyDetailsBean;
import com.lsfb.signln.My.MyFragment;
import com.lsfb.signln.R;
import com.lsfb.signln.Statistics.StatisticsFragment;
import com.lsfb.signln.Utils.LittleUtils;
import com.lsfb.signln.Utils.URLString;
import com.lsfb.signln.View.MyFragmentActivity;
import com.zgscwjm.lsfbbasetemplate.Event.EventAnnotation;
import com.zgscwjm.lsfbbasetemplate.Event.LsfbEvent;
import com.zgscwjm.lsfbbasetemplate.LsfbAppManager;
import com.zgscwjm.lsfbbasetemplate.internet.BaseInternet;
import com.zgscwjm.lsfbbasetemplate.utils.DensityUtils;
import com.zgscwjm.lsfbbasetemplate.utils.LsfbLog;
import com.zgscwjm.lsfbbasetemplate.utils.T;
import com.zgscwjm.lsfbbasetemplate.view.bottombar.BottomBarItem;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2018/1/18 0018.
 */

public class IndexActivity extends MyFragmentActivity {

    private BottomBarItem bar1, bar2, bar3, bar4;
    private List<Fragment> mFragments;
    private String permissionInfo;
    public ImmersionBar mImmersionBar;
    private final int SDK_PERMISSION_REQUEST = 127;

    @Override
    public void initView() {
        LsfbLog.e("测试1114");
        LsfbEvent.getInstantiation().register2(this);

//        LsfbLog.e("定位服务启动");
//        Intent startIntent = new Intent(this,LongRunningService.class);
//        startService(startIntent);


        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.statusBarColor(R.color.theme_color).init();
        setIsScroll(false);
        LsfbEvent.getInstantiation().register2(this);
        ColorStateList cls = getResources().getColorStateList(R.color.index_bottom_btn);
        Rect rect = new Rect(0, 0, DensityUtils.dp2px(this, 20), DensityUtils.dp2px(this, 20));

        ArrayList list = new ArrayList<BottomBarItem>();

        bar1 = new BottomBarItem();
        bar1.setId(View.generateViewId());
        bar1.setColorStateList(cls);
        bar1.setName("定位");
        bar1.setIsCheck(true);
        bar1.setImgRes(R.drawable.bottom_location);
        list.add(bar1);

        bar2 = new BottomBarItem();
        bar2.setId(View.generateViewId());
        bar2.setName("申请");
        bar2.setColorStateList(cls);
        bar2.setImgRes(R.drawable.bottom_leave);
        list.add(bar2);

        bar3 = new BottomBarItem();
        bar3.setId(View.generateViewId());
        bar3.setName("统计");
        bar3.setColorStateList(cls);
        bar3.setImgRes(R.drawable.bottom_statistics);
        list.add(bar3);

        bar4 = new BottomBarItem();
        bar4.setId(View.generateViewId());
        bar4.setName("我的");
        bar4.setColorStateList(cls);
        bar4.setImgRes(R.drawable.bottom_my);
        list.add(bar4);

        bar1.setBounds(rect);
        bar2.setBounds(rect);
        bar3.setBounds(rect);
        bar4.setBounds(rect);

        getButtonBar().setPadding(0, 16, 0, 16);
        getButtonBar().initButtonBar(list, R.color.white_color);
        mFragments = new ArrayList<>();
        setMainBackground();
        initFragments();
        getMyInfo();
    }

    /**
     * Fragment添加内容
     */
    public void initFragments() {
        //定位
        mFragments.add(new LocationFragment());
        //请假
        mFragments.add(new LeaveFragment());
        //统计
        mFragments.add(new StatisticsFragment());
        //我的
        mFragments.add(new MyFragment());

        setTabFragments(mFragments);
    }

    @Override
    public void initEvent() {

    }


//    private String pictureName = "/sdcard/" + LittleUtils.username + ".jpg";

    private String SAVE_PIC_PATH = Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED) ? Environment.getExternalStorageDirectory().getAbsolutePath() : "/mnt/sdcard";
    private String pictureName = SAVE_PIC_PATH + "/face.jpg";//保存的确切位置

    @Override
    public void initData() {
        LsfbLog.e("文件名:" + pictureName);
        //判断文件是否存在
//        File file = new File(pictureName);
//        if (!file.exists()) {
//            getData();
//        }
        getPersimmions();
    }

    /**
     * 得到签到图片
     */
    public void getData() {
        HashMap<String, String> hashMap = new HashMap<String, String>();

        new BaseInternet().getData_Get(URLString.FACEIMG, hashMap, String.class, new SignInFileEvent(), true, false);
    }

    @EventAnnotation
    public void SignInEvent(SignInFileEvent event) {
        switch (event.getCode()) {
            case 200:
                getHttpBitmap(URLString.IMAGES + event.getData());
                break;
            case 1006:
                T.showShort(this, "您的账号已在其它设备登录，请重登录");
                LittleUtils.exit(this);
                startActivity(new Intent(this, LoginActivity.class));
                break;
            default:
                LsfbLog.e(event.getMsg());
                break;
        }
    }

    /**
     * 下载图片
     *
     * @param url
     * @return
     */
    public void getHttpBitmap(final String url) {
        LsfbLog.e("下载图片");

        final Bitmap[] bitmap = {null};

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL pictureUrl = new URL(url);
                    InputStream in = pictureUrl.openStream();
                    bitmap[0] = BitmapFactory.decodeStream(in);
                    LsfbLog.e("下载成功？");
                    in.close();
                    savePicture(bitmap[0]);//保存
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }

    /**
     * 保存图片
     *
     * @param bitmap
     */
    public void savePicture(Bitmap bitmap) {
        LsfbLog.e("保存图片");

//        File file = new File(pictureName);
        FileOutputStream out;
        try {
            out = new FileOutputStream(pictureName);
//            out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
            LsfbLog.e("保存成功？");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取权限的方法,批量获取
     */
    @TargetApi(23)
    private void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            /***
             * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
             */
            // 定位精确位置
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }
    }

    /**
     * 添加批量获取列表
     *
     * @param permissionsList
     * @param permission
     * @return
     */
    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)) {
                return true;
            } else {
                permissionsList.add(permission);
                return false;
            }
        } else {
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void tabOnClick(View view, ViewPager viewPager) {
        int id = view.getId();
        if (id == bar1.getId()) {
            viewPager.setCurrentItem(0);
        } else if (id == bar2.getId()) {
            viewPager.setCurrentItem(1);
        } else if (id == bar3.getId()) {
            viewPager.setCurrentItem(2);
        } else if (id == bar4.getId()) {
            viewPager.setCurrentItem(3);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        initbarset();
        getMyInfo();
    }

    /**
     * 用于判断是否第一次登录
     */
    private void getMyInfo() {
        HashMap<String, String> hashMap = new HashMap<String, String>();
        new BaseInternet().getData_Get(URLString.INFO, hashMap, MyDetailsBean.class, new InfoEvent<MyDetailsBean>(), true, false);
    }

    @EventAnnotation
    public void MyDetailsEvent(InfoEvent<MyDetailsBean> event) {
        switch (event.getCode()) {
            case 200:
                switch (event.getData().getIsFirst()) {
                    //不是第一次登录
                    case 0:
                        break;
                    //第一次登录
                    case 1:
                        startActivity(new Intent(this, FirstFaceActivity.class).putExtra("type", "1"));
                        break;
                }
                break;
            case 1006:
                T.showShort(this, "您的账号已在其它设备登录，请重登录");
                LittleUtils.exit(this);
                startActivity(new Intent(this, LoginActivity.class));
                break;
            default:
                T.showShort(this, event.getMsg());
                break;
        }
    }


    @Override
    protected void onDestroy() {
        mImmersionBar.destroy();  //在BaseActivity里销毁
        super.onDestroy();
        LsfbEvent.getInstantiation().unregister2(this);
    }


    private void initbarset() {
        switch (viewPager.getCurrentItem()) {
            case 0:
                getButtonBar().setCheckById(bar1.getId());
                break;
            case 1:
                getButtonBar().setCheckById(bar2.getId());
                break;
            case 2:
                getButtonBar().setCheckById(bar3.getId());
                break;
            case 3:
                getButtonBar().setCheckById(bar4.getId());
                break;
        }
    }

    //点击退出弹出确认提示框
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            dialog();
            return true;
        }
        return true;
    }

    protected void dialog() {

//    通过AlertDialog.Builder这个类来实例化我们的一个AlertDialog的对象
        AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.MyAlertDialogStyle);
//    设置Title的图标
//        builder.setIcon(R.mipmap.ic_launcher);
//    设置Title的内容
        builder.setTitle("温馨提示");
//    设置Content来显示一个信息
        builder.setMessage("确定要退出应用吗？");
//    设置一个PositiveButton
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                LsfbAppManager.getAppManager().finishAllActivity();
                android.os.Process.killProcess(android.os.Process.myPid());

            }
        });
//    设置一个NegativeButton
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
//    显示出该对话框
        builder.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LsfbLog.e("requestCode" + requestCode);
        LsfbLog.e("resultCode" + resultCode);
        mFragments.get(viewPager.getCurrentItem()).onActivityResult(requestCode, resultCode, data);
    }
}
